package com.codingxyz.simple.classLoader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {

    private String  path;

    private String className;

    public MyClassLoader(String path,String classLoaderName){

        this.path = path;
        this.className = classLoaderName;
    }

    @Override
    public Class findClass(String  name){
        byte[] b = loadClassData(name);
        return defineClass(name,b,0,b.length);
    }

    private byte[] loadClassData(String name) {


        InputStream in = null;
        ByteArrayOutputStream out = null;

        String classpath = path+"\\"+name+".class";
        try {

            in = new FileInputStream(new File(classpath));
            out = new ByteArrayOutputStream();
            int i = 0;
            while ((i = in.read())!=-1){
                out.write(i);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                out.close();
                in.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return out.toByteArray();
    }


}
